import 'package:flutter/material.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/video.dart';
import 'package:netflix_social/providers/video_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:provider/provider.dart';

class DownloadsTab extends StatefulWidget {
  const DownloadsTab({Key? key}) : super(key: key);

  @override
  State<DownloadsTab> createState() => _DownloadsTabState();
}

class _DownloadsTabState extends State<DownloadsTab> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final videoProvider = Provider.of<VideoProvider>(context);
    
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      appBar: AppBar(
        backgroundColor: AppTheme.backgroundColor,
        elevation: 0,
        title: Text(
          '下载',
          style: Theme.of(context).textTheme.headlineSmall,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              // 导航到下载设置页面
              // 实际项目中，这里可能会导航到下载设置页面
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: AppTheme.netflixRed,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.grey,
          tabs: const [
            Tab(text: '已下载'),
            Tab(text: '正在下载'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 已下载
          _buildCompletedDownloadsList(videoProvider.downloadedVideos),
          // 正在下载
          _buildInProgressDownloadsList(videoProvider.downloadingVideos),
        ],
      ),
    );
  }

  Widget _buildCompletedDownloadsList(List<Video> videos) {
    if (videos.isEmpty) {
      return _buildEmptyState(
        icon: Icons.download_done,
        title: '没有已下载的内容',
        message: '你可以下载影片和剧集，以便在没有网络的时候观看。',
        buttonText: '查找可下载的内容',
        onButtonPressed: () {
          // 导航到可下载内容页面
          // 实际项目中，这里可能会导航到探索页面
        },
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: videos.length,
      itemBuilder: (context, index) {
        final video = videos[index];
        return _buildDownloadedVideoItem(video);
      },
    );
  }

  Widget _buildInProgressDownloadsList(List<Map<String, dynamic>> downloadingItems) {
    if (downloadingItems.isEmpty) {
      return _buildEmptyState(
        icon: Icons.download,
        title: '没有正在下载的内容',
        message: '你下载的内容将在这里显示。',
        buttonText: '查找可下载的内容',
        onButtonPressed: () {
          // 导航到可下载内容页面
          // 实际项目中，这里可能会导航到探索页面
        },
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: downloadingItems.length,
      itemBuilder: (context, index) {
        final downloadItem = downloadingItems[index];
        final video = downloadItem['video'] as Video;
        final progress = downloadItem['progress'] as double;
        return _buildDownloadingVideoItem(video, progress);
      },
    );
  }

  Widget _buildEmptyState({
    required IconData icon,
    required String title,
    required String message,
    required String buttonText,
    required VoidCallback onButtonPressed,
  }) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 80,
              color: Colors.grey[600],
            ),
            const SizedBox(height: 16),
            Text(
              title,
              style: Theme.of(context).textTheme.titleLarge,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            Text(
              message,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Colors.grey[400],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: onButtonPressed,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.netflixRed,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
              ),
              child: Text(buttonText),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDownloadedVideoItem(Video video) {
    final thumbnailHeight = 80.0;
    final thumbnailWidth = thumbnailHeight * 16 / 9;

    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: InkWell(
        onTap: () {
          // 播放下载的视频
          Navigator.pushNamed(
            context,
            AppConstants.playerRoute,
            arguments: {
              'videoId': video.id,
              'isOffline': true,
            },
          );
        },
        child: Row(
          children: [
            // 缩略图
            Stack(
              children: [
                Container(
                  width: thumbnailWidth,
                  height: thumbnailHeight,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    image: DecorationImage(
                      image: NetworkImage(video.thumbnailUrl),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Positioned.fill(
                  child: Center(
                    child: Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.black.withOpacity(0.5),
                      ),
                      child: const Icon(
                        Icons.play_arrow,
                        color: Colors.white,
                        size: 28,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(width: 16),
            // 视频信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    video.title,
                    style: Theme.of(context).textTheme.titleMedium,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    video.description,
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: Colors.grey[400],
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Text(
                        '${video.duration} 分钟',
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: Colors.grey[500],
                        ),
                      ),
                      const SizedBox(width: 16),
                      Text(
                        '${video.fileSize} MB',
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: Colors.grey[500],
                        ),
                      ),
                      const Spacer(),
                      IconButton(
                        icon: const Icon(
                          Icons.more_vert,
                          color: Colors.grey,
                        ),
                        onPressed: () {
                          _showVideoOptionsBottomSheet(context, video);
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDownloadingVideoItem(Video video, double progress) {
    final thumbnailHeight = 80.0;
    final thumbnailWidth = thumbnailHeight * 16 / 9;

    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Row(
        children: [
          // 缩略图
          Container(
            width: thumbnailWidth,
            height: thumbnailHeight,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              image: DecorationImage(
                image: NetworkImage(video.thumbnailUrl),
                fit: BoxFit.cover,
              ),
            ),
          ),
          const SizedBox(width: 16),
          // 视频信息和进度
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  video.title,
                  style: Theme.of(context).textTheme.titleMedium,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  '${(progress * 100).toStringAsFixed(0)}% 已下载',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[400],
                  ),
                ),
                const SizedBox(height: 8),
                LinearPercentIndicator(
                  percent: progress,
                  lineHeight: 4,
                  backgroundColor: Colors.grey[800],
                  progressColor: AppTheme.netflixRed,
                  padding: EdgeInsets.zero,
                  barRadius: const Radius.circular(2),
                  animation: true,
                  animateFromLastPercent: true,
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Text(
                      '${(video.fileSize ?? 0) * progress ~/ 1} / ${video.fileSize ?? 0} MB',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey[500],
                      ),
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(
                        Icons.pause,
                        color: Colors.grey,
                      ),
                      onPressed: () {
                        // 暂停下载
                        // 实际项目中，这里可能会调用暂停下载的方法
                      },
                      iconSize: 20,
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                    const SizedBox(width: 16),
                    IconButton(
                      icon: const Icon(
                        Icons.cancel,
                        color: Colors.grey,
                      ),
                      onPressed: () {
                        // 取消下载
                        // 实际项目中，这里可能会调用取消下载的方法
                      },
                      iconSize: 20,
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _showVideoOptionsBottomSheet(BuildContext context, Video video) {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.cardColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.play_arrow),
              title: const Text('播放'),
              onTap: () {
                Navigator.pop(context);
                Navigator.pushNamed(
                  context,
                  AppConstants.playerRoute,
                  arguments: {
                    'videoId': video.id,
                    'isOffline': true,
                  },
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.delete),
              title: const Text('删除下载'),
              onTap: () {
                Navigator.pop(context);
                // 删除下载
                // 实际项目中，这里可能会调用删除下载的方法
              },
            ),
            ListTile(
              leading: const Icon(Icons.info),
              title: const Text('查看详情'),
              onTap: () {
                Navigator.pop(context);
                Navigator.pushNamed(
                  context,
                  AppConstants.videoDetailRoute,
                  arguments: video.id,
                );
              },
            ),
          ],
        );
      },
    );
  }
}
